<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";

import { demo } from "@/api/demo/demo";
import { Cat, Dog } from "@/api/demo";

defineOptions({
  name: "Test-Demo"
});

interface RuleForm {
  name: string;
}

const form = reactive<RuleForm>({
  name: "嘟嘟"
});
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "参数不可为空", trigger: "blur" }]
});

const doDemo = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  formEl.validate(valid => {
    if (valid) {
      const cat: Cat = {
        name: form.name
      };
      const request = {
        param: cat
      };
      console.debug(request);
      demo(request).then(response => {
        const dog: Dog = response.data;
        form.name = dog.name;
      });
    } else {
      ElMessage.error("参数校验失败");
      return false;
    }
  });
};
</script>

<template>
  <el-card>
    <el-form :model="form" ref="formRef" :rules="rules">
      <el-form-item prop="name">
        <el-input
          v-model="form.name"
          :rows="2"
          type="textarea"
          clearable
          placeholder="Please input"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="doDemo(formRef)">
          测试
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
